from info import constants
from info.models import User, News,Category
from info.modules.index import index_blu
# from info import redis_store
from flask import render_template, current_app, send_file, session, redirect, request, jsonify,g
from info.utils.common import user_login
from info.utils.response_code import RET





@index_blu.route("/news_list")
def get_news_list():
    # 接收参数
    cid = request.args.get("cid")
    page = request.args.get("page",1)
    per_page = request.args.get("per_page",10)

    # 校验参数合法性
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)

    except Exception as e:
        current_app.logger.error(e)

        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")

    # filters = []
    # if cid !=1:
    #     filters.append((News.category_id == cid))


    # 查出的新闻（要关系分类）（安创建时间排序）
    filters = [News.status == 0]
    if cid != 1:  # 查询的不是最新的数据
        # 需要添加条件
        filters.append(News.category_id == cid)

    # 3. 查询数据
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    news_list = paginate.items
    current_page = paginate.page
    total_page = paginate.pages

    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())

    data = {
        "news_dict_li":news_dict_li,
        "current_page":current_page,
        "total_page":total_page
    }

    return jsonify(errno=RET.OK,errmsg="OK",data=data)









@index_blu.route("/")
@user_login
def index():

    # user_id = session.get("user_id")
    # user = None
    #
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)
    user = g.user
    # 显示点击排行
    clicks_news = []
    try:
        clicks_news = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS).all()  # [obj, obj, obj]
    except Exception as e:
        current_app.logger.error(e)

    # [obj, obj, obj] --> [{}, {}, {}, {}]
    clicks_news_li = []

    for news_obj in clicks_news:
        clicks_news_dict = news_obj.to_basic_dict()
        clicks_news_li.append(clicks_news_dict)



        # 2、显示新闻分类
    categorys = []
    try:
        categorys = Category.query.all()  # [obj, obj]
    except Exception as e:
        current_app.logger.error(e)

    # categorys_li = []  # [{}, {}, {}]
    # for category in categorys:
    #     categorys_dict = category.to_dict()
    #     categorys_li.append(categorys_dict)
    # 使用列表表达式返回[{}, {}, {}]数据
    categorys_li = [category.to_dict() for category in categorys]




    data = {
        "user_info":user.to_dict() if user else None,
        "clicks_news_li":clicks_news_li,
        "categorys":categorys_li

        }

   # redis_store.set('name','laowang')
    return render_template("news/index.html",data=data)



@index_blu.route("/favicon.ico")
def favicon():
    # 重定向
    # return ("/static/news/favicon.ico")
    return current_app.send_static_file("news/favicon.ico")
    # return send_file("news/favicon.ico")
